package com.toobulkeh.search;
//package com.toobulkeh.search;

import org.htmlparser.*;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

public class ImageSearch {
	
	private String queryString, searchString;
	private Parser parser;
	private NodeList list;
	private int startAt;
	
	public ImageSearch(String searchString) {
		//changes spaces to + for query string
		this.searchString = searchString.replace(' ', '+');
		startAt = 0;
		
	}
	
	/**
	 * Returns 20 images at a time. Queried again returns 20 more
	 * @return
	 */
	public ImageSearchResult search() {
		//construct query string
		queryString = "http://images.google.com/images?hl=en&start="+startAt+"&imgsz=2mp&q="+searchString;
		startAt+=20;
		ImageSearchResult toRet = new ImageSearchResult();
		
		try {
			parser = new Parser (queryString);
			list = parser.parse(new TagNameFilter("img"));
		} catch(ParserException e) {
			System.err.println("Poop. Parser Exception. Start over!");
		}
		
		Node tmpNode;
		for(int i = 0; i < list.size(); i++) {
			tmpNode = list.elementAt(i);
			if(tmpNode.getText().contains("gstatic")) {
				String[] splits = tmpNode.getText().split(":[^/]");
				splits = splits[2].split(" ");
				
				//System.out.println(tmpNode.getText());
				String[] thumb = tmpNode.getText().split(" ");
				//System.out.println(thumb[1].substring(4));
				toRet.addImage("h"+splits[0],thumb[1].substring(4));
			}
		}
		return toRet;
	}
	
	public ImageSearchResult search(ImageSearchResult curr) {
		if(curr == null) {
			return search();
		} else {
			curr.combine(search());
			return curr;
		}
	}

	public static void main(String[] args) {
		ImageSearch search = new ImageSearch("Italian pizza parlor");
		ImageSearchResult result = search.search();
		int count = 1;
		
		for(int i = 0; i < result.getSize(); i++) {
			System.out.println( count + ": "+result.getNextImage());
			count++;
		}
		
		result = search.search();
		
		for(int i = 0; i < result.getSize(); i++) {
			System.out.println( count + ": "+result.getNextImage());
			count++;
		}
		
		result = search.search();
		
		for(int i = 0; i < result.getSize(); i++) {
			System.out.println( count + ": "+result.getNextImage());
			count++;
		}
	}
	
}
